using System;
using System.Diagnostics;
using System.IO;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools
{
    class LogTraceWriter : TextWriterTraceListener
    {
        readonly string
            logFile;
        int
            currentDay;

        public LogTraceWriter(string logFile)
        {
            this.logFile = logFile;

            var
                now = DateTime.UtcNow;

            this.currentDay = now.Day;

            CreateListener(now);
        }

        void CreateListener(DateTime now, int attempt = 0)
        {
            try
            {
                base.Writer = new StreamWriter(this.logFile + '_' + now.ToString("yyyyMMdd") + (attempt == 0 ? string.Empty : "_" + attempt) + ".log", true);
            }
            catch (Exception)
            {
                if (attempt < 3)    // this is when file is used by another process
                    CreateListener(now, attempt + 1);
                else
                    throw;
            }
        }

        void CheckRolling()
        {
            var
                now = DateTime.UtcNow;

            if (now.Day != currentDay)  // day changed, create new log
            {
                this.currentDay = now.Day;

                base.Writer.Flush();
                base.Close();

                CreateListener(now);
            }
        }

        public override void WriteLine(string text)
        {
            CheckRolling();
            base.WriteLine(text);
        }

        public override void Fail(string text)
        {
            CheckRolling();
            base.Fail(text);
        }
    }
}